/*
 *  txdnet.cn tonydon
 * 
 */
package cn.txdnet.txcms.service;

import cn.txdnet.txcms.dict.ChannelType;
import cn.txdnet.txcms.domain.Catalogs;
import cn.txdnet.txcms.domain.Links;
import cn.txdnet.txcms.mapper.CatalogsMapper;
import cn.txdnet.txcms.mapper.DHIndexMapper;
import cn.txdnet.txcms.query.ViewSiteListQuery;
import cn.txdnet.txweb.basedao.mybatis.MybatisUtil;
import cn.txdnet.txweb.utils.CollectionUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;

/**
 *
 * @author txdnet
 */
public class DHIndexService {

    /**
     * 导航站点列表数据
     *
     * @param query
     * @return
     */
    public static Map querySiteList(ViewSiteListQuery query) {
        query.filter();
        SqlSession sqlsn = MybatisUtil.getSqlSession();
        DHIndexMapper mapper = sqlsn.getMapper(DHIndexMapper.class);
        CatalogsMapper catalogsMapper = sqlsn.getMapper(CatalogsMapper.class);
        Catalogs topCatalogs = catalogsMapper.queryCatalogsByCid(query.getCid());
        if (topCatalogs == null || topCatalogs.getInfotype().byteValue() != ChannelType.LINKS.getValue()) {
            sqlsn.close();
            return Collections.emptyMap();
        }
        query.setCataloglevel(CatalogsLevelService.getLevelByCatalog(topCatalogs));
        String topCatalogsName = topCatalogs.getCname();
        List<?> list = mapper.querySiteList(query);
        List<?> secondCatalogsList = catalogsMapper.queryCatalogsListByRid(topCatalogs.getCid());
        sqlsn.close();

        Map page = new HashMap();
        page.put("topCatalogsName", topCatalogsName);
        if (CollectionUtil.isNotEmpty(list)) {
            if (CollectionUtil.isNotEmpty(secondCatalogsList)) {
                page.put("secondCatalogsList", secondCatalogsList);
                // 按CID分组
                for (Object o : secondCatalogsList) {
                    Integer cid = ((Catalogs) o).getCid();
                    List groupList = groupListByCid(list, cid);
                    page.put(cid, groupList);
                }
            } else {
                page.put("list", list);
            }
        }
        return page;
    }

    /**
     * 按照CI分组列表
     *
     * @param cid
     * @return
     */
    private static List groupListByCid(List list, Integer cid) {
        List groupList = new ArrayList();
        for (Object o : list) {
            if (((Links) o).getCid().equals(cid)) {
                groupList.add(o);
            }
        }
        return groupList;
    }
}
